﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NCrawler.Extensions;

namespace ZCrawler
{
    public class ZRuleDerived : ZBasicRule
    {
        public string DerivedString { get; set; }
        public ZRuleDerived() { }
        public ZRuleDerived(string fn) : base(fn) { }
        public override string Process<T>(T source)
        {
            ZResult r = source as ZResult;
            string result = "";
            string[] fragments = DerivedString.Split('+');
            foreach(string frag in fragments)
            {
                if(frag.StartsWith("#FAppend#"))                 //Field
                {
                    string fn = frag.Replace("#FAppend#", "");
                    string val = r.DATA[fn].ToString();
                    result = AnalysisCompute(result, val);
                }       
                else                                             //Constance
                {
                    result = AnalysisCompute(result, frag);
                }
            }
            return result;
        }

        public override string Description()
        {
            return "Derived String : {0}".FormatWith(DerivedString);
        }

        private string AnalysisCompute(string str,string val)
        {
            string result = str;
            double num;
            if (double.TryParse(val, out num))
            {
                if (result.IsNullOrEmpty())
                    result = val.ToString();
                else
                {
                    double res_num;
                    if (double.TryParse(result, out res_num))
                    {
                        result = (res_num + num).ToString();
                    }
                }
            }
            else
            {
                result += val;
            }
            return result;
        }
    }
}
